<script setup lang="tsx">
import { ref, inject } from 'vue';
import { useI18n } from 'vue-i18n';
import MyTable from '@/components/myTable/index.vue';
import OperatingBox from '@/components/operatingBox/index.vue';
import QueryBox from '@/components/queryBox/index.vue';
import { formGroup } from '@/components/formDialog/FormDialog';
import FormDialogGroup from '@/components/formDialog/FormDialogGroup.vue';
import { Space, Link, Dropdown, MessagePlugin } from 'tdesign-vue-next';
import { ChevronDownSIcon, AddIcon, Delete1Icon, SearchIcon } from 'tdesign-icons-vue-next';
import { getUserList, addUser, editUser, getUserInfo, deleteUser, resetPwd } from '@/api/system/user';
const addDateRange = inject<typeof addDateRange>('addDateRange');
const DownSIcon = () => <ChevronDownSIcon />;
const { t } = useI18n();

const data = ref([]);
const columns = [
  {
    colKey: 'row-select',
    type: 'multiple' as const,
    width: 50,
  },
  {
    title: '用户编号',
    colKey: 'userId',
  },
  {
    title: '用户名称',
    colKey: 'userName',
  },
  {
    title: '用户昵称',
    colKey: 'nickName',
  },
  // {
  //   title: '部门',
  //   colKey: 'deptId',
  // },
  {
    title: '手机号码',
    colKey: 'phonenumber',
  },
  {
    title: '状态',
    colKey: 'status',
  },
  {
    title: '创建时间',
    colKey: 'createTime',
  },
  {
    title: '操作',
    colKey: 'op',
  },
];

const pagination = ref({
  defaultCurrent: 1,
  defaultPageSize: 10,
  total: 0,
});

interface FormDataType {
  userName: string | null;
  phonenumber: string | number | null;
  status: string | number | null;
  pageNum: string | number | null;
  pageSize: string | number | null;
}
const INITIAL_QUERYFORM: FormDataType = {
  userName: undefined,
  phonenumber: undefined,
  status: undefined,
  pageNum: null,
  pageSize: null,
};
const queryForm = ref({ ...INITIAL_QUERYFORM });

const dateRange = ref<string[]>([]);

const render = () => (
  <>
    <OperatingBox>
      <t-button icon={() => <AddIcon />} onClick={() => unAdd()}>
        新增
      </t-button>
      <t-button theme="danger" icon={() => <Delete1Icon />} onClick={() => deleteClickOp(deleteId.value, true)}>
        批量删除
      </t-button>
    </OperatingBox>
    <QueryBox onReset={onReset} onSearch={unGetUserList}>
      <t-input v-model={queryForm.value.userName} placeholder="用户名称" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-input v-model={queryForm.value.phonenumber} placeholder="手机号码" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-select v-model={queryForm.value.status} placeholder="状态">
        <t-option label="正常" value="0" />
        <t-option label="停用" value="1" />
      </t-select>
      <t-date-range-picker v-model={dateRange.value} placeholder="创建日期范围" />
    </QueryBox>
    <MyTable
      columns={columns}
      data={data.value}
      v-model:pagination={pagination.value}
      v-model:selectedRowKeys={deleteId.value}
      rowKey="userId"
      onUnGetList={unGetUserList}
    >
      {{
        status: (slotProps: any) => (
          <t-tag theme={slotProps.row.status == 0 ? 'primary' : 'danger'} variant="light">
            {slotProps.row.status == 0 ? '正常' : '停用'}
          </t-tag>
        ),
        op: (slotProps: any) => (
          <Space>
            <Link theme="primary" onClick={() => unEditUser(slotProps)}>
              修改
            </Link>
            <Link theme="danger" onClick={() => deleteClickOp(slotProps, false)}>
              {t('pages.detailCard.detail.form.delete')}
            </Link>
            <Dropdown options={options} trigger="click" onClick={() => clickHandler(slotProps)}>
              <Space>
                <Link suffix-icon={() => <DownSIcon />}>更多</Link>
              </Space>
            </Dropdown>
          </Space>
        ),
      }}
    </MyTable>
  </>
);

const unGetUserList = async () => {
  try {
    queryForm.value.pageNum = pagination.value.defaultCurrent;
    queryForm.value.pageSize = pagination.value.defaultPageSize;
    const res = await getUserList({
      ...addDateRange?.(queryForm.value, dateRange.value),
    });
    data.value = res.rows;
    pagination.value = {
      ...pagination.value,
      total: res.total,
    };
  } catch (e) {
    console.log(e);
  }
};

unGetUserList();

const onReset = () => {
  queryForm.value = { ...INITIAL_QUERYFORM };
  dateRange.value = [];
  unGetUserList();
};

const options = [
  {
    content: '重置密码',
    value: 'resetPasswords',
  },
];
const roleList = ref([]);
/** 添加对话框 */
const formObj = new formGroup();
const unAdd = async () => {
  try {
    const res = await getUserInfo('');
    roleList.value = res.roles;
    formObj.show('添加用户', {}, '添加用户');
  } catch (e) {
    console.error('获取角色列表失败:', e);
    MessagePlugin.error('获取角色列表失败');
  }
};
formObj.add<any>(
  '添加用户',
  '添加用户',
  {
    data: {
      password: '123456',
      status: '0',
    },
  },
  async (body) => {
    await addUser(body.data);
    unGetUserList();
  },
  {
    nickName: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
    userName: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
    password: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      {
        validator: (val: string) => val.length >= 5 && val.length <= 20,
        message: '密码长度应介于5至20位之间',
        trigger: 'blur',
      },
    ],
  },
);

// 用户详情
const unEditUser = async (slotProps: any) => {
  try {
    let res = await getUserInfo(slotProps.row.userId);
    roleList.value = res.data.roles;
    res.data.roleIds = res.roleIds;
    formObj.show(
      '编辑用户',
      {
        ...res.data,
      },
      '编辑用户',
    );
  } catch (e) {
    console.error('获取用户详情失败:', e);
    MessagePlugin.error('获取用户详情失败');
  }
};

// 重置密码
const clickHandler = (value: any) => {
  formObj.show(
    '重置密码',
    {
      userId: value.row.userId,
      userName: value.row.userName,
    },
    '重置密码',
  );
};

formObj.add<any>(
  '重置密码',
  '重置密码',
  {},
  async (body) => {
    await resetPwd(body.data);
    unGetUserList();
  },
  {
    password: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      {
        validator: (val: string) => val.length >= 5 && val.length <= 20,
        message: '密码长度应介于5至20位之间',
        trigger: 'blur',
      },
    ],
  },
);

formObj.add<any>(
  '编辑用户',
  '编辑用户',
  {},
  async (body) => {
    await editUser(body.data);
    unGetUserList();
  },
  {
    nickName: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
  },
);

// 删除
const confirmVisible = ref(false);
const deleteId = ref([]);
const onConfirmDelete = () => {
  let ids = deleteId.value.join(',');
  deleteUser(ids).then(() => {
    confirmVisible.value = false;
    MessagePlugin.success('删除成功');
    unGetUserList();
  });
};

const deleteClickOp = (value: any, isSingle: boolean) => {
  if (isSingle && !value.length) {
    MessagePlugin.warning('请先勾选数据');
    return;
  }
  confirmVisible.value = true;
  deleteId.value = isSingle ? value : [value.row.userId];
};

const onCancel = () => {
  if (deleteId.value.length < 2) {
    deleteId.value = [];
  }
};
</script>

<template>
  <div>
    <render />
    <!-- 对话框 -->
    <FormDialogGroup :form-obj="formObj">
      <template #default="{ formData, item }">
        <template v-if="item == '添加用户' || item == '编辑用户'">
          <t-form-item label="用户昵称" name="nickName">
            <t-input v-model="formData.nickName" placeholder="用户昵称" />
          </t-form-item>
          <t-form-item label="用户名称" name="userName" v-if="item == '添加用户'">
            <t-input v-model="formData.userName" placeholder="用户名称" />
          </t-form-item>
          <t-form-item label="用户密码" name="password" v-if="item == '添加用户'">
            <t-input type="password" v-model="formData.password" placeholder="用户密码" />
          </t-form-item>
          <t-form-item label="角色" name="roleIds">
            <t-select multiple v-model="formData.roleIds">
              <t-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
            </t-select>
          </t-form-item>
          <t-form-item label="手机号" name="phonenumber">
            <t-input v-model="formData.phonenumber" placeholder="手机号" />
          </t-form-item>
          <t-form-item label="状态" name="status">
            <t-radio-group v-model="formData.status">
              <t-radio value="0">正常</t-radio>
              <t-radio value="1">停用</t-radio>
            </t-radio-group>
          </t-form-item>
        </template>
        <template v-if="item == '重置密码'">
          <t-form-item label="新密码" name="password">
            <t-input v-model="formData.password" :placeholder="`请输入 ${formData.userName} 的新密码`" />
          </t-form-item>
        </template>
      </template>
    </FormDialogGroup>
    <t-dialog
      v-model:visible="confirmVisible"
      header="确认删除当前所选项目？"
      body="删除后，数据将被清空，且无法恢复"
      @confirm="onConfirmDelete"
      :on-cancel="onCancel"
    />
  </div>
</template>
